<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-select
        v-model="listQuery.class_type"
        placeholder="班级类型"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in classType"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select> -->
      <el-select
        v-model="listQuery.year"
        placeholder="年份"
        clearable
        class="filter-item"
        style="width: 90px"
      >
        <el-option v-for="item in years" :key="item" :label="item" :value="item" />
      </el-select>
      <el-date-picker
        v-model="listQuery.begin_time"
        type="month"
        class="filter-item"
        value-format="yyyy-MM-dd"
        placeholder="开班开始日期"
      ></el-date-picker>
      <el-date-picker
        v-model="listQuery.end_time"
        type="month"
        class="filter-item"
        value-format="yyyy-MM-dd"
        placeholder="开班结束日期"
      ></el-date-picker>
      <el-input
        v-model="listQuery.search"
        placeholder="名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :loading="listLoading"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleAdd"
      >新增</el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>-->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      @sort-change="sortChange"
    >
      <el-table-column type="index" prop="id" width="40" align="center" sortable="custom" />
      <el-table-column label="类型" class-name="status-col">
        <template slot-scope="{row}">
          <el-tag
            :type="row.class_type | statusFilter"
          >{{ classType[row.class_type]['display_name'] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="年份" prop="year" align="center" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.year }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.class_name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="开班时间"
        prop="class_start_time"
        width="120"
        align="center"
        sortable="custom"
      >
        <template slot-scope="{row}">
          <span>{{ row.class_start_time | dateFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程收费" prop="class_fee" width="110" align="center" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.class_fee }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="最大人数" prop="max_num" width="110" align="center" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.max_num }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="班级人数" width="80" align="center">
        <template slot-scope="{row}">
          <span>{{ row.student_number }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="报名开始时间"
        prop="sign_start_time"
        width="130"
        align="center"
        sortable="custom"
      >
        <template slot-scope="{row}">
          <span>{{ row.sign_start_time | dateFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="报名结束时间"
        prop="sign_end_time"
        width="130"
        align="center"
        sortable="custom"
      >
        <template slot-scope="{row}">
          <span>{{ row.sign_end_time | dateFormat }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="120" align="center" label="备注">
        <template slot-scope="{row}">
          <span>{{ row.remarks }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="120"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button size="mini" icon="el-icon-document" type="primary" @click="handleDetail(row)">详情</el-button>
          <el-dropdown trigger="click">
            <el-button size="small">
              <i class="el-icon-more"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <span @click="handleEdit(row)">
                  <i class="el-icon-edit"></i>编辑
                </span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span @click="handleUpload(row)">
                  <i class="el-icon-upload"></i>上传图片
                </span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span @click="handleDelete(row)">
                  <i class="el-icon-delete"></i>删除
                </span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.page_size"
      @pagination="getList"
    />

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" @closed="handleCloseForm">
      <el-form
        ref="dataForm"
        :model="info"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="班级类型">
          <el-select v-model="info.class_type" class="filter-item" placeholder="请选择">
            <el-option
              v-for="item in classType.slice(1)"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-select v-model="info.year" class="filter-item" placeholder="请选择" @change="handleChangeYear">
            <el-option v-for="item in years" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="class_name">
          <el-input v-model="info.class_name" />
        </el-form-item>
        <el-form-item label="开班时间" prop="class_start_time">
          <el-date-picker v-model="info.class_start_time" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="课程收费" prop="class_fee">
          <el-input v-model="info.class_fee" />
        </el-form-item>
        <!-- <el-form-item label="最大人数" prop="max_num">
          <el-input v-model="info.max_num" />
        </el-form-item> -->
        <el-form-item label="报名开始时间" prop="sign_start_time">
          <el-date-picker v-model="info.sign_start_time" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="报名结束时间" prop="sign_end_time">
          <el-date-picker v-model="info.sign_end_time" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="info.remarks" :autosize="{ minRows: 4, maxRows: 10}" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="dialogLoading" @click="info.id ? edit() : add()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="dialogUploadTitle"
      :visible.sync="dialogUploadVisible"
      width="80%"
      @closed="handleCloseUpload"
    >
      <el-upload
        :headers="uploadHeader"
        :action="uploadUrl"
        name="photo"
        :file-list="photoList"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :before-remove="handleRemove"
        :on-success="handleScuess"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <div v-if="imgVisible" style="padding: 10px; border: 1px solid #eee;">
        <img width="100%" :src="dialogImageUrl" style="box-shadow: 10px 10px 5px #888888;" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  fetchAdd,
  fetchEdit,
  fetchDelete,
  fetchPhoto,
  fetchDeletePhoto
} from '@/api/classes'
import waves from '@/directive/waves' // waves directive
import drag from '@/directive/el-drag-dialog'
import { parseTime, range } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { classType } from '@/utils/dataType'
import { getToken } from '@/utils/auth'

export default {
  name: 'ClassList',
  components: { Pagination },
  directives: { waves, drag },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '1': 'warning',
        '2': 'success'
      }
      return statusMap[status]
    },
    dateFormat(time) {
      return time === 0 ? '-' : parseTime(time, '{y}-{m}-{d}')
    }
  },
  data() {
    return {
      visible: false,
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      uploadHeader: null,
      uploadUrl: null,
      listQuery: {
        student_number: 1,
        page: 1,
        page_size: 10,
        class_type: undefined,
        year: undefined,
        begin_date: undefined,
        end_date: undefined,
        search: undefined,
        status: undefined,
        sort: '-id'
      },
      changeFlag: false, // 是否修改和新增过得flag
      years: range(2019, 2025),
      dialogTitle: '新增班级',
      info: {},
      classType,
      downloadLoading: false,
      dialogLoading: false,
      dialogFormVisible: false,
      dialogUploadVisible: false,
      dialogUploadTitle: '上传图片',
      photoList: [],
      imgVisible: false,
      dialogImageUrl: ''
    }
  },
  created() {
    this.listQuery.class_type = this.$route.meta.class_type;
    this.uploadHeader = { Authorization: getToken() }
    this.getList()
  },
  methods: {
    reset() {
      this.listQuery = this.$options.data().listQuery
      this.info = {}
    },
    async getList() {
      try {
        this.listLoading = true
        const { data } = await fetchList(this.listQuery)
        const { data: list, total } = data
        this.list = list
        this.total = total
        this.listLoading = false
      } catch (e) {
        this.listLoading = false
      }
    },
    async edit() {
      try {
        this.dialogLoading = true
        await fetchEdit(this.info)
        this.dialogLoading = false
        this.$message({ message: '修改成功', type: 'success' })
        this.changeFlag = true
        this.dialogFormVisible = false
      } catch (e) {
        this.dialogLoading = false
      }
    },
    async add() {
      try {
        this.dialogLoading = true
        await fetchAdd(this.info)
        this.dialogLoading = false
        this.$message({ message: '新增成功', type: 'success' })
        // 可以连续添加班级
        this.infoInit()
        this.changeFlag = true
        // this.reset()
        // this.dialogFormVisible = false
        // await this.getList()
      } catch (e) {
        // this.dialogLoading = false
      }
    },
    infoInit() {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      this.info = {
        class_type: 1,
        year: date.getFullYear(),
        class_name: `${year}年${month}月`
      }
    },
    handleAdd() {
      this.infoInit()
      this.dialogTitle = '新增班级'
      this.dialogFormVisible = true
    },
    handleChangeYear(year) {
      this.info.class_name = `${year}年1月`
    },
    handleEdit(row) {
      this.info = row
      this.dialogTitle = `修改班级:${row.class_name}`
      this.dialogFormVisible = true
    },
    handleDetail(row) {
      const { class_type, id } = row
      let name;
      if (class_type === 1) {
        name = 'StudentUi'
      } else if (class_type === 2) {
        name = 'StudentH5'
      }
      this.$router.push({
        name,
        params: {
          id
        }
      })
    },
    handleCloseForm() {
      this.reset()
      if (this.changeFlag) {
        this.changeFlag = false
        this.getList()
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    async handleUpload(row) {
      // 先加载数据在打开弹框
      const { id, class_name } = row
      try {
        const { data = [] } = await fetchPhoto(id)
        this.photoList = data.map(item => ({
          uid: item.id,
          name: item.file_name,
          url: item.http_path
        }))
      } catch (e) {
        console.log(e)
      }
      this.dialogUploadTitle = `上传图片:${class_name}`
      this.uploadUrl = `${process.env.VUE_APP_BASE_API}/admin/classes/${id}/photos`
      this.dialogUploadVisible = true
    },
    handleRemove(file, fileList) {
      return new Promise((resolve, reject) => {
        this.$confirm('此操作不可恢复，确认要删除照片吗？')
          .then(_ => {
            try {
              ;(async () => {
                await fetchDeletePhoto(file.uid)
                this.$message({ message: '删除成功', type: 'success' })
                resolve()
              })()
            } catch (e) {
              this.$message({ message: '删除失败', type: 'error' })
              resolve()
            }
          })
          .catch(_ => reject())
      })
    },
    handleScuess(response, file, fileList) {
      const { data } = response
      file.uid = data.id
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.imgVisible = true
    },
    handleCloseUpload() {
      this.photoList = []
      this.dialogImageUrl = ''
      this.imgVisible = false
    },
    handleDelete(row) {
      this.$confirm(`此操作不可恢复，确认要删除【${row.class_name}】班级吗?`)
        .then(_ => {
          try {
            ;(async () => {
              await fetchDelete(row.id)
              this.$message({ message: '删除成功', type: 'success' })
              await this.getList()
            })()
          } catch (e) {
            this.$message({ message: '删除失败', type: 'error' })
          }
        })
        .catch(_ => {})
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        this.sort(prop, order)
      }
    },
    sort(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sort = `+${prop}`
      } else {
        this.listQuery.sort = `-${prop}`
      }
      this.handleFilter()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
